package com.ruoyi.basic;

import java.io.*;

public class TransientTest {
    public static void main(String[] args) {
        try {
            SerializeUser();
            DeSerializeUser();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //序列化
    private static void SerializeUser() throws IOException {
        User user = new User();
        user.setId(1);
        user.setUsername("哪吒编程");
        user.setAge(28);
        user.setPassword("123456");
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("E://data.txt"));
        oos.writeObject(user);
        oos.close();
        System.out.println("普通字段序列化：username=  " + user.getUsername());
        System.out.println("添加了transient关键字序列化：password=  " + user.getPassword());
    }

    //反序列化
    private static void DeSerializeUser() throws IOException, ClassNotFoundException {
        File file = new File("E://data.txt");
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
        User user = (User) ois.readObject();
        System.out.println("普通字段反序列化：username=  " + user.getUsername());
        System.out.println("添加了transient关键字反序列化：password=  " + user.getPassword());
    }
}
